import { sys } from "cc";

export interface SSS_GameStorageData {
    userId: string;
    nickName: string;
    provinceId: number;
    avatar: string;

    // sound_on: boolean;
    // music_on: boolean;
    // vibrate_on: boolean;
    // skin_data: any;
}

/**存储类，用于存储需要本地保存的数据 */
class SSS_GameStorage {
    static GameName: string = `SSS`;

    data: SSS_GameStorageData = null;
    defaultValue: SSS_GameStorageData = null;

    private static _instance: SSS_GameStorage = null;

    public static get instance(): SSS_GameStorage {
        this._instance = this._instance || new SSS_GameStorage();
        return this._instance;
    }

    initData() {
        this.InitDefaultData();

        let dataStr = sys.localStorage.getItem(`${SSS_GameStorage.GameName}_GameStorage`);
        if (!dataStr || dataStr === '') {
            this.clearData();
        }
        else {
            this.data = JSON.parse(dataStr);
            this.saveData();
        }

        this.SetEveryData();
    }

    // 初始化默认值
    InitDefaultData() {
        this.defaultValue = {
            userId: '',
            nickName: "",
            provinceId: 0,
            avatar: "",
        };
    }

    SetEveryData() {
        for (let key in this.defaultValue) {
            let defaultValue = this.defaultValue[key];
            let dataValue = this.data[key];
            // console.log(key, defaultValue, dataValue);
            if (dataValue === null || dataValue === undefined) {
                this.data[key] = defaultValue;
            }
        }
        this.saveData();
    }

    clearData() {
        this.data = Object.assign({}, this.defaultValue);
        console.log(`this.data`, this.data);
    }

    saveData() {
        let dataStr = JSON.stringify(this.data);
        sys.localStorage.setItem(`${SSS_GameStorage.GameName}}_GameStorage`, dataStr);
    }
}

export default SSS_GameStorage.instance;